import { tt } from "../../../ttapi_interface/ttapi.js";
import * as tt2 from "../../../ttapi_layer2/ttlayer2.js";
import * as EUI from "../../eui/EUI.js"
import { EditorBase, EditorInfo, IEditorUI } from "../editorbase.js";


export class Image_EditorUI extends EditorBase {
    constructor() {
        super();
    }

    private _tex_Preview: tt.ITexture;
    private _tex_srcurl: string;
    async InitAsync(): Promise<{ ui: tt2.QUI_IElement, info: EditorInfo }> {

        let con = new tt2.QUI_Container();
        con.localRect.setAsFill();

        let abuf = await tt2.QExt_IO.File_Read(this._filename, false);

        this._tex_srcurl = URL.createObjectURL(new Blob([abuf]));
        let img = await tt2.QFrame_ResMgr.LoadStandaloneSpriteAsync(this._tex_srcurl)

        this._tex_Preview = img.tex;//tex 有资源句柄，要记下来手动释放


        let tt = new tt2.QUI_Image(img);
        let panel = new tt2.QUI_Panel_Scroll();
        panel.addChild(tt);
        panel.panelWidth = img.pixelwidth;
        panel.panelHeight = img.pixelheight;
        panel.dragDirection = tt2.QUI_DragDriection.Both;
        panel.localRect.setHPosFill();
        panel.localRect.setVPosFill(0, 0);
        con.addChild(panel);
        let outinfo = "Tex size:" + this._tex_Preview.getWidth() + " X " + this._tex_Preview.getHeight();
        return { ui: con, info: { "text": outinfo, canopen: true } };
    }
    async CleanAsync(): Promise<void> {
        if (this._tex_Preview != null) {
            this._tex_Preview.Destory();
            this._tex_Preview = null;
        }
        this._tex_srcurl = null;

        if (this.editor_canvas != null) {
            this.editor_canvas.ClearTex();
        }
    }

    editor_toolbox: EUI.EUI_Bitmap_Toolbox;
    editor_canvas: EUI.EUI_Bitmap_Editor;

    async Open(): Promise<boolean> {
        this._container.removeChildAll();

        this.editor_toolbox = new EUI.EUI_Bitmap_Toolbox();
        this._container.addChild(this.editor_toolbox);
        this.editor_toolbox.OnChange = (tool) => {
            this.editor_canvas.tool = tool;
        }

        let split = EUI.EUI_Style.CreateHSplit();

        split.splitPos = 0.7;
        split.localRect.setHPosFill(26);
        this._container.addChild(split);

        this.editor_canvas = new EUI.EUI_Bitmap_Editor();
        this.editor_canvas.localRect.setAsFill();

        split.getPanel1().addChild(this.editor_canvas);

        let buffer = await tt.loader.LoadImageDataAsync(this._tex_srcurl, false);

        this.editor_canvas.InitBuffer(buffer.width, buffer.height, buffer.data);
        this.editor_canvas.OnChange = () => {
            this._change = true;
        }
        return true;
    }




}